/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.action.retrievedefault;
import com.inspur.edp.bef.api.be.IBEContext;
import com.inspur.edp.bef.core.DotNetToJavaStringHelper;
import com.inspur.edp.bef.core.action.base.ActionUtil;
import com.inspur.edp.bef.spi.action.AbstractAction;
import com.inspur.edp.bef.spi.entity.builtinimpls.BefEntityResInfoImpl;
import com.inspur.edp.bef.spi.entity.columnconfig.ColumnGenerateConfigLoader;
import com.inspur.edp.bef.spi.entity.columnconfig.ColumnGenerateInfo;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.cef.spi.entity.resourceInfo.EntityResInfo;
import java.util.UUID;

public class CreateChildDataAction extends AbstractAction<IEntityData>
{
	private String childCode;
	private String dataID;
	public CreateChildDataAction(IBEContext beContext, String childCode, String dataID)
	{
		super(beContext);
		this.childCode = childCode;
		this.dataID = dataID;
	}

	private String getID()
	{
		if (DotNetToJavaStringHelper.isNullOrEmpty(dataID) == false)
		{
			return dataID;
		}
		return getColumnId();
	}

	@Override
	public void execute()
	{
IEntityData data = ActionUtil.getRootEntity(this).createChildEntityData(childCode, getID());
		setResult(ActionUtil.getRootEntity(this).createChildAccessor(childCode, data));
	}


	private String getColumnId(){
		if(this.getBEContext()==null||this.getBEContext().getModelResInfo()==null || this.getBEContext().getModelResInfo().getCustomResource(this.childCode)==null)
			return UUID.randomUUID().toString();
		EntityResInfo  resInfo= this.getBEContext().getModelResInfo().getCustomResource(childCode);
		if(!(resInfo instanceof BefEntityResInfoImpl))
			return UUID.randomUUID().toString();
		ColumnGenerateInfo columnGenerateInfo=((BefEntityResInfoImpl)resInfo).getColumnGenerateInfo();
		return ColumnGenerateConfigLoader.getId(columnGenerateInfo);
	}
}
